from django.db.models import Q, F
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action

from djangoStudy.tool import build_query
from djangoStudy.db import DBUtils

from task.models import Task
from rest_framework.response import Response
from .serializers import TaskSerializer,TaskUserSerializer
from task.models import TaskUser
from user.models import User

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
    permission_classes = (permissions.AllowAny,)

    
    @action(detail=False, methods=['POST'])
    def search(self, request):
        """获取任务信息，支持按名称搜索"""
        # 获取所有可能的搜索参数
        data = request.data
        print(data)
        title = request.data.get('title')
        user_id = request.data.get('user_id')
        print(title)
        # 如果没有任何搜索参数，返回400错误
        if not title and not user_id:
            return Response({"message": "请提供一个搜索参数"}, status=status.HTTP_400_BAD_REQUEST)
        # 构建查询条件
        query = Q()
        query &= Q(title__icontains=title)

        query &= Q(users__id=user_id)
        # 执行查询，同时获取模块名和语言名的别名
        tasks = Task.objects.filter(query).annotate(
            m_name=F('module__name'),
            l_name=F('language__name')
        ).distinct()  # 添加distinct防止多对多关联导致的重复结果
        # 序列化结果
        serializer = self.get_serializer(tasks, many=True)
        # 返回结果
        return Response({
            "message": "查询成功",
            # "count": tasks.count(),
            "data": serializer.data
        })

    @action(detail=False, methods=['POST'])
    def show(self, request, *args, **kwargs):
        """
        根据查询参数来查找相关任务，并展示
        """
        # 拿到查询参数
        data = request.data
        print(data)
        base_sql = """
            SELECT 
                t.id as id,
                tu.answer as answer,
                tu.is_solve as checked,
                t.title AS title,
                t.detail AS detail,
                t.completed AS completed,
                tu.status AS status,
                l.name AS l_name,
                m.name AS m_name
            FROM 
                tb_task t
            inner JOIN 
                tb_language l ON t.language_id = l.id
            inner JOIN 
                tb_module m ON t.module_id = m.id 
            inner JOIN
                tb_task_user tu on t.id = tu.task_id
        """

        total_sql = """
        SELECT 
                count(*)
            FROM 
                tb_task t
            inner JOIN 
                tb_language l ON t.language_id = l.id
            inner JOIN 
                tb_module m ON t.module_id = m.id 
            inner JOIN
                tb_task_user tu on t.id = tu.task_id
        """

        # 构建查询
        data_sql, data_params = build_query(base_sql, data)
        # print(data_sql, data_params)
        # 老师端查询所有学生提交的任务

        results = DBUtils.select_all(data_sql, data_params)
        # 构建总条数sql
        total_sql, total_params = build_query(total_sql, data, True)
        total_result = DBUtils.select_one(total_sql, total_params)
        # print(total_params)
        total = total_result["count(*)"] if total_result else 0
        return Response(data={"data": results,  "total": total}, status=status.HTTP_200_OK)

    @action(detail=False, methods=['POST'])
    def language_detail(self, request, *args, **kwargs):
        user_id = request.data.get('user_id')
        sql = """
            SELECT distinct tl.name
            FROM tb_language tl
            inner JOIN
                tb_task ts on ts.language_id = tl.id
            inner JOIN
                tb_task_user ttu on ttu.task_id = ts.id 
            inner JOIN
                auth_user au on ttu.user_id = au.id
            WHERE au.id = %s
        """

        data = DBUtils.select_all(sql, args=(user_id,))
        # print(data)
        return Response(data={"data": data}, status=status.HTTP_200_OK)
    @action(detail=False, methods=['POST'])
    def set_code(self, request, *args, **kwargs):
        code = request.data.get('code')
        is_solve = request.data.get('checked')
        user_id = request.data.get('user_id')
        task_id = request.data.get('task_id')
        print(request.data)
        # 选中是或会做为 1 代表不会做, 将 status 设为2
        if is_solve == 1:
            status = 2
        else:
            status = 3
        sql = """
        UPDATE tb_task_user 
        SET answer = %s, is_solve = %s, status = %s 
        WHERE user_id = %s AND task_id = %s;
        """
        data = DBUtils.insert(sql, args=(code, is_solve, status, user_id, task_id))
        print(data)

        return Response(data={"message": "保存成功"}, status=200)

    @action(detail=False, methods=['POST'])
    def update_status(self, request, *args, **kwargs):
        """修改 开始和结束 状态"""
        status = request.data.get('status')
        user_id = request.data.get('user_id')
        task_id = request.data.get('task_id')
        print(status, user_id, task_id)
        if status == 0:
            status = 1
        elif status == 4:
            status = 5

        sql = """
        update tb_task_user set status = %s where user_id = %s and task_id = %s;
        """
        data = DBUtils.update(sql, args=(status, user_id, task_id))

        print(data)

        return Response(data={"message": "修改成功"},status=200)

    @action(detail=False, methods=['GET'])
    def get_status(self, request, *args, **kwargs):
        """
        获取所有用户的任务状态统计数据，排除异常题（状态为-1）
        返回格式：
        [
            {
                id: 1,
                email: 'zhangsan@sina.com',
                name: '张三',
                task_total_count: 100,
                task_count_1: 30,  # 已完成的任务数
                task_count_2: 50,  # 需讲解的任务数
                task_ncount: 20,   # 未完成的任务数
                task_rate: 39,     # 完成率
            },
            ...
        ]
        """
        try:
            # 获取所有用户
            users = User.objects.filter(is_active=True, is_delete=False)
            result = []

            for user in users:
                # 获取该用户的所有任务
                user_tasks = TaskUser.objects.filter(user=user)

                # 计算总任务数
                task_total_count = user_tasks.count()

                if task_total_count:
                    # 计算未开始的任务数
                    task_count_0 = user_tasks.filter(status=0).count()

                    # 计算进行中的任务数
                    task_count_1 = user_tasks.filter(status=1).count()

                    # 计算已提交的任务数
                    task_count_3 = user_tasks.filter(status=3).count()

                    # 计算已检查的任务数
                    task_count_4 = user_tasks.filter(status=4).count()

                    # 计算已完成的任务数（状态为5）
                    task_count_5 = user_tasks.filter(status=5).count()

                    # 计算需讲解的任务数（状态为2）
                    task_count_2 = user_tasks.filter(status=2).count()

                    # 计算完成率（已完成/总数 * 100）
                    task_rate = int(
                        ((task_count_4 + task_count_5) / task_total_count) * 100) if task_total_count > 0 else 0

                    # 添加到结果列表
                    result.append({
                        'id': user.id,
                        'email': user.email,
                        'name': user.name or user.username,
                        'task_total_count': task_total_count,
                        'task_count_0': task_count_0,
                        'task_count_1': task_count_1,
                        'task_count_2': task_count_2,
                        'task_count_3': task_count_3,
                        'task_count_4': task_count_4,
                        'task_count_5': task_count_5,
                        'task_rate': task_rate,
                    })

            return Response(result, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({"message": f"获取任务状态失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['POST'])
    def explain(self, request, *args, **kwargs):
        """查询状态等于2的数据"""
        # 使用Django ORM替代原来的SQL查询，并预加载关联的task, language和module数据
        task_users = TaskUser.objects.filter(status=2).select_related(
            'task', 'user', 'task__language', 'task__module'
        )

        # 按任务分组
        tasks_dict = {}
        for task_user in task_users:
            task_id = task_user.task.id
            
            # 如果这个任务还没在字典中，添加它
            if task_id not in tasks_dict:
                tasks_dict[task_id] = {
                    'id': task_id,
                    'title': task_user.task.title,
                    'detail': task_user.task.detail,
                    'completed': task_user.task.completed,
                    'l_name': task_user.task.language.name if task_user.task.language else None,
                    'm_name': task_user.task.module.name if task_user.task.module else None,
                    'status': task_user.status,
                    'students': []
                }

            # 获取用户名
            user_name = task_user.user.name or task_user.user.username

            # 检查该用户是否已经在students列表中
            student_exists = False
            for student in tasks_dict[task_id]['students']:
                if student['name'] == user_name:
                    student_exists = True
                    break

            # 如果用户不在列表中，添加它
            if not student_exists and user_name:
                # 添加学生对象，只包含name字段
                tasks_dict[task_id]['students'].append({
                    'name': user_name
                })

        # 将字典转换为列表
        result = list(tasks_dict.values())

        # 返回结果
        return Response(data={"data": result}, status=200)

    @action(detail=False, methods=['POST'])
    def updatestatus(self, request, *args, **kwargs):
        """将任务状态更新为已检查(4)"""
        # 获取请求数据
        task_id = request.data.get('task_id')
        if not task_id:
            return Response({"message": "缺少必要参数task_id"}, status=status.HTTP_400_BAD_REQUEST)
        try:
            # 查找所有对应的TaskUser记录
            task_users = TaskUser.objects.filter(task_id=task_id)
            if not task_users.exists():
                return Response({"message": "未找到对应的任务记录"}, status=status.HTTP_404_NOT_FOUND)
            # 批量更新状态为4（已检查）
            count = task_users.update(status=4)
            return Response({"message": f"成功更新{count}条记录的状态为已检查"}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({"message": f"更新失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['POST'])
    def update_state(self, request, *args, **kwargs):
        user_id = request.data.get('user_id')
        task_id = request.data.get('task_id')
        status = int(request.data.get('status'))
        print(user_id, task_id, status)
        if status == 0:
            status = 1
        elif status == 4:
            status = 5

        sql = """
            update tb_task_user set status = %s where user_id = %s and task_id = %s
        """

        DBUtils.update(sql, (status, user_id, task_id))

        return Response(status=200)

    @action(detail=False, methods=['POST'])
    def assignTask(self, request, *args, **kwargs):
        """
        将任务分配给指定用户，支持一次分配多个任务
        参数:
        - task_id: 任务ID，可以是单个ID或多个ID的列表
        - user_id: 用户ID
        """
        try:
            # 获取任务ID和用户ID
            task_id = request.data.get('task_id')
            user_id = request.data.get('user_id')

            # 验证参数
            if not task_id or not user_id:
                return Response({"message": "缺少必要参数task_id或user_id"}, status=status.HTTP_400_BAD_REQUEST)

            # 检查用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return Response({"message": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)

            # 将task_id转换为列表，如果不是列表的话
            if not isinstance(task_id, list):
                task_id = [task_id]

            success_count = 0
            failed_count = 0
            results = []

            # 遍历任务ID列表
            for tid in task_id:
                # 检查任务是否存在
                try:
                    task = Task.objects.get(id=tid)
                except Task.DoesNotExist:
                    failed_count += 1
                    results.append({"task_id": tid, "status": "失败", "reason": "任务不存在"})
                    continue

                # 检查任务是否已经分配给该用户
                task_user_exists = TaskUser.objects.filter(task=task, user=user).exists()
                if task_user_exists:
                    failed_count += 1
                    results.append({"task_id": tid, "status": "失败", "reason": "该任务已经分配给该用户"})
                    continue

                # 创建任务分配记录
                task_user = TaskUser.objects.create(
                    task=task,
                    user=user,
                    status=0  # 初始状态为"未开始"
                )

                success_count += 1
                results.append({
                    "task_id": tid,
                    "status": "成功",
                    "task_title": task.title,
                    "task_user_id": task_user.id
                })

            # 返回结果
            message = f"成功分配 {success_count} 个任务给用户 {user.username}"
            if failed_count > 0:
                message += f"，{failed_count} 个任务分配失败"

            return Response({
                "message": message,
                "results": results
            }, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({"message": f"分配任务失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
